<template>
    <el-dialog ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="60%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="选择鱼塘" prop="fishPondId">
                <el-select v-model="ruleForm.fishPondId" :disabled="addEditFlag == 'edit'" filterable clearable
                    class="w100p" @change="handleChangeFishPond">
                    <el-option v-for="(item, index) in fishPondList" :key="index" :label="item.pondName"
                        :value="item.fishPondId" />
                </el-select>
            </el-form-item>
            <el-form-item label="选择批次" prop="batchId">
                <el-select v-model="ruleForm.batchId" :disabled="addEditFlag == 'edit'" filterable clearable class="w100p"
                    @change="batchPondInfoList">
                    <el-option v-if="ruleForm.fishPondId == item.fishPondId" v-for="(item, index) in batchList"
                        :key="index" :label="item.batchName" :value="item.batchId" />
                </el-select>
            </el-form-item>
            <el-form-item label="选择品种" prop="fishVarietyId">
                <el-select v-model="ruleForm.fishVarietyId"  :disabled="addEditFlag=='edit'" filterable clearable class="w100p"
                    @change="handleChangeFishVariety">
                    <el-option v-for="item, index in fishVarietyList" :key="index" :label="item.fishVarietyName"
                        :value="item.fishVarietyId" />
                </el-select>
            </el-form-item>
            <el-form-item label="估产比例">
                <el-input v-model="ruleForm.rate" disabled placeholder="请先选择鱼塘/批次"></el-input>
            </el-form-item>
            <el-form-item label="估重区间">
                <el-input v-model="ruleForm.weightRange" disabled placeholder="请先选择鱼塘/批次"></el-input>
            </el-form-item>
            <el-form-item label="估产重量" prop="predictWeight">
                <el-input v-model="ruleForm.predictWeight" placeholder="请输入估产重量"></el-input>
            </el-form-item>
            <el-form-item label="估产人" prop="staffId">
                <el-select v-model="ruleForm.staffId" filterable clearable class="w100p" @change="handleChangeStaff">
                    <el-option v-for="item, index in staffList" :key="index" :label="item.staffName"
                        :value="item.staffId" />
                </el-select>
            </el-form-item>
            <el-form-item label="估产日期" prop="predictDate">
                <el-date-picker v-model="ruleForm.predictDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
                    :picker-options="pickerOptions" class="w100p">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <SaveDraftBox ref="saveDraft" v-if="addEditFlag == 'add' && dialogVisible" :formData="ruleForm"
                @pushData="pushData">
            </SaveDraftBox>
            <el-button type="primary" @click="submitForm" :disabled="isDisabled">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import hangingWaterYieldEstimation from '@/api/production-management/hanging-water-yield-estimation.js';
import InPondEstimationHandingApi from "@/api/in-pond-estimation/in-pond-estimation-handing";
import pondStockingManagement from '@/api/production-management/pond-stocking-management.js';
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        fishPondList: {
            type: Array,
            default: () => {
                return []
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return []
            }
        },
        specificationList: {
            type: Array,
            default: () => {
                return []
            }
        },
        staffList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        let checkNum = (rule, value, callback) => {
            if (value) {
                if (Number(value) > 0 && Number(value) <= 99999) {
                    callback();
                } else if (Number(value) > 99999) {
                    callback(new Error('请输入小于100000的数'));
                } else {
                    callback(new Error('请输入大于0的数'));
                }
            } else {
                callback(new Error('请输入数值'));
            }
        };
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() >= Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            isDisabled: false,
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            fishVarietyList: [],
            rules: {
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                predictWeight: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                samplingDate: [
                    { required: true, message: '请选择估产时间', trigger: 'change' }
                ],
                fishPondId: [
                    { required: true, message: '请选择鱼塘', trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择操作人', trigger: 'change' }
                ],
                fishVarietyId: [
                    { required: true, message: '请选择品种', trigger: 'change' }
                ],
                predictDate: [
                    { required: true, message: '请选择日期', trigger: 'change' }
                ],
            }
        }
    },
    computed: {},
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            this.isDisabled = false;
            if (this.addEditFlag == 'add') {
                this.resetForm();
                this.addEditApi = hangingWaterYieldEstimation.add;
                this.addEditName = '添加';
                this.getInitRulFormData();
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data };
                this.addEditApi = hangingWaterYieldEstimation.edit;
                this.addEditName = '编辑';
                this.batchPondInfoList(this.data.batchId);
            }
        },
        pushData(data) {
            this.ruleForm = { ...data };
            this.batchPondInfoList(this.ruleForm.batchId);
            this.$nextTick(() => {
                this.$refs.ruleForm.clearValidate();
            })
        },
        async batchPondInfoList(batchId) {
            this.isDisabled = false;
            if (!batchId) {
                this.$set(this.ruleForm, 'fishVarietyId', '');
                this.$set(this.ruleForm, 'specificationId', '');
                this.$set(this.ruleForm, 'fishVarietyName', '');
                return
            }
            let { data: fishVarietyList } = await pondStockingManagement.batchPondInfoList({ batchId });
            this.fishVarietyList = fishVarietyList || [];
            this.fishVarietyNumObj = {}
            this.fishVarietyList = this.fishVarietyList.filter(item => {
                this.fishVarietyNumObj[item.fishVarietyId] = item.num
                return item.num > 0
            })
            if (this.addEditFlag == 'add') {
                this.fishVarietyList.forEach((item, index) => {
                    index == 0 && this.$set(this.ruleForm, 'fishVarietyId', item.fishVarietyId);
                    index == 0 && this.$set(this.ruleForm, 'fishVarietyName', item.fishVarietyName);
                });
            }
            this.getTimeConfig(batchId, this.ruleForm.fishVarietyId);
        },
        async getTimeConfig(batchId, fishVarietyId) {
            if (batchId && fishVarietyId) {
                let { data, success, message } = await InPondEstimationHandingApi.generateHangingBreedPredictYield({ batchId, fishVarietyId })
                if (success) {
                    this.$set(this.ruleForm, 'minRate', data.minRate)
                    this.$set(this.ruleForm, 'maxRate', data.maxRate)
                    this.$set(this.ruleForm, 'rate', data.minRate + '% ~ ' + data.maxRate + '%')
                    this.$set(this.ruleForm, 'maxWeight', data.maxWeight)
                    this.$set(this.ruleForm, 'minWeight', data.minWeight)
                    this.$set(this.ruleForm, 'weightRange', data.minWeight + ' ~ ' + data.maxWeight)
                    this.$set(this.ruleForm, 'predictYieldConfigId', data.predictYieldConfigId)
                } else {
                    this.isDisabled = true;
                    this.$message.warning(message);
                }
            }
        },
        addMaterial() {
            let length = this.ruleForm.predictYieldDetailList?.length || 0
            if (length) {
                this.$set(this.ruleForm.predictYieldDetailList, length, {
                    weight: null, num: null, specificationId: null
                })
            }
        },
        delMaterial(index) {
            let list = this.ruleForm.predictYieldDetailList;
            list.splice(index, 1);
            this.$set(this.ruleForm, 'predictYieldDetailList', list)
        },
        //初始化一些表单数据
        getInitRulFormData() {
            let id = sessionStorage.getItem('staffId') || null;
            let params = {
                staffId: id == 'null' ? '' : Number(id),
                predictDate: this.$formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss')
            }
            this.$set(this, 'ruleForm', params);
        },
        //选择鱼塘时提示用户是否存在该关联批次
        handleChangeFishPond(id) {
            let rut = this.batchList.find(item => item.fishPondId == id);
            let batchId = rut?.batchId;
            this.batchPondInfoList(batchId);
            this.$set(this.ruleForm, 'batchId', batchId || '');
            !rut && this.$message.warning('该鱼塘暂无批次!');
        },
        //选择品种时提示用户是否存在该品种规格
        handleChangeFishVariety(id) {
            let rut = this.specificationList.find(item => item.fishVarietyId == id);
            let specificationId = rut?.specificationId
            this.getTimeConfig(this.ruleForm.batchId, id);
            this.$set(this.ruleForm, 'specificationId', specificationId || '');
            !rut && this.$message.warning('该鱼种暂未配置规格!');
        },
        //获取估产人姓名
        handleChangeStaff(id) {
            let rut = this.staffList.find(item => item.staffId == id);
            let staffName = rut?.staffName
            this.$set(this.ruleForm, 'staffName', staffName || '');
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.addEditApi({ ...this.ruleForm }).then(res => {
                        let msg = res.success ? '操作成功' : '操作失败'
                        this.$message[res.success ? 'success' : 'warning'](res.message || msg)
                        res.success && this.cancel();
                        //提交数据时删除保存的记录
                        res.success && this.addEditFlag == 'add' && this.$refs.saveDraft.delByKey();
                    }).catch(err => {
                        this.$message.error(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.fishVarietyList = []
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.icon {
    font-size: 24px;
    line-height: 30px;
    margin-left: 15px;
}
</style>